package com.example.dirviesystem.student.service;

import com.example.dirviesystem.entity.PracticeRecord;
import com.example.dirviesystem.entity.Question;
import com.example.dirviesystem.entity.SimulateExamRecord;
import com.example.dirviesystem.entity.StudentInfo;
import com.example.dirviesystem.repository.PracticeRecordRepository;
import com.example.dirviesystem.repository.SimulateExamRepository;
import com.example.dirviesystem.repository.StudentInfoRe;
import com.example.dirviesystem.repository.StudentQuestionRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class StudentExamService {
    private final PracticeRecordRepository practiceRecordRepository;
    private final SimulateExamRepository simulateExamRepository;
    private final StudentQuestionRepository studentQuestionRepository;
    private final StudentInfoRe studentInfoRe;

    public void savePracticeRecord(Long studentId, Long questionId, String selectedAnswer) {
        StudentInfo student = studentInfoRe.findById(studentId).orElseThrow();
        Question question = studentQuestionRepository.findById(questionId).orElseThrow();

        PracticeRecord practiceRecord = new PracticeRecord();
        practiceRecord.setStudent(student);
        practiceRecord.setQuestion(question);
        practiceRecord.setSelectedAnswer(selectedAnswer);
        practiceRecord.setCorrect(selectedAnswer.equals(question.getCorrectAnswer()));
        practiceRecord.setSubject(question.getSubject());
        practiceRecord.setAnsweredAt(LocalDateTime.now());

        practiceRecordRepository.save(practiceRecord);
    }
    public SimulateExamRecord startSimulateExam(Long studentId, String subject) {
        Optional<SimulateExamRecord> unfinished = simulateExamRepository.findTopByStudentIdAndSubjectAndSubmittedFalseOrderByStartTimeDesc(studentId, subject);
        return unfinished.orElseGet(() -> {
            SimulateExamRecord exam = new SimulateExamRecord();
            exam.setStudent(studentInfoRe.findById(studentId).orElseThrow());
            exam.setSubject(subject);
            exam.setStartTime(LocalDateTime.now());
            exam.setSubmitted(false);
            return simulateExamRepository.save(exam);
        });
    }
    public SimulateExamRecord submitSimulateExam(Long examId, int correctCount, int totalQuestions, int score) {
        SimulateExamRecord exam =simulateExamRepository.findById(examId).orElseThrow();
        exam.setCorrectCount(correctCount);
        exam.setTotalQuestions(totalQuestions);
        exam.setScore(score);
        exam.setSubmitted(true);
        exam.setSubmitTime(LocalDateTime.now());
        return simulateExamRepository.save(exam);
    }

    public double getAverageScore(Long studentId, String subject) {
        List<SimulateExamRecord> exams = simulateExamRepository.findByStudentIdAndSubjectAndSubmittedTrue(studentId, subject);
        return exams.isEmpty() ? 0 : exams.stream().mapToInt(SimulateExamRecord::getScore).average().orElse(0);
    }
    public List<PracticeRecord> getPracticeAnswers(Long studentId, String subject) {
        return practiceRecordRepository.findByStudentIdAndSubject(studentId, subject);
    }
    public Optional<SimulateExamRecord> getPendingSimulateExam(Long studentId, String subject) {
        return simulateExamRepository.findTopByStudentIdAndSubjectAndSubmittedFalseOrderByStartTimeDesc(studentId, subject);
    }

}
